import { Common } from 'UtilsCommon';
import { EnvConfig } from 'Configs';

export function getResponseData(d, resKey) {
    const blSuccess = !(d && d.isSuccess === false);

    if (!blSuccess) return d;

    if (d.Token) {
        window.token = d.Token;
        Common.setStorage(EnvConfig.tokenKey, d.Token, 60 * 24);
    }

    if (d.Data) d = d.Data;

    let obj = null;
    if (d.Exception || d.Message) {
        const msg = d.Exception || d.Message;
        obj = { isSuccess: false, message: msg };
        if (d.IsReLogin) obj.isReLogin = true;
    }
    else if (d.Ack) {
        if (d.Ack.IsSuccess) {
            if (resKey && d.hasOwnProperty(resKey)) obj = d[resKey];
            else if (d.EntityData && d.EntityData.hasOwnProperty(resKey)) obj = d.EntityData[resKey];
            else obj = d;
        }
        else {
            if (d.Ack.Code === -100) {
                Common.removeStorage(EnvConfig.tokenKey);
                window.loginUser = null;
                window.token = null;
                if (Common.getStorage("reload") !== "true") {
                    Common.setStorage("reload", "true");
                    window.location.reload();
                } else setTimeout(() => Common.setStorage("reload", "false"), 1000);

                obj = {};
            }
            else obj = { isSuccess: false, message: d.Ack.Message || '请求异常' };
        }
    }
    else if (d.result === false && d.msg) {
        obj = { ...d, isSuccess: false, message: d.msg };
    }
    else if (d.result && d.data) {
        obj = d.data;
    }
    else if (resKey) {
        if (d && d.hasOwnProperty(resKey)) obj = d[resKey];
        else obj = d;
    }
    else if (d) obj = d;
    else obj = { isSuccess: false, message: "请求异常！" };

    return obj;
}

export function getResponse(d, resKey) {
    return Promise.resolve(getResponseData(d, resKey));
}

export function getErrorResponse(res) {
    const msg = res && res.message ? res.message : res;
    return Promise.resolve({ isSuccess: false, message: msg });
}